<template>
  <StarfieldBackground>
    <div class="register-wrapper">
      <div class="register-card">
        <div class="register-header">
          <h2>用户注册</h2>
          <p>创建您的账户，开始使用项目管理系统</p>
        </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        label-width="80px"
        size="large"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名（3-50个字符）"
            :prefix-icon="User"
            @blur="checkUsernameAvailable"
          />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="registerForm.name"
            placeholder="请输入真实姓名"
            :prefix-icon="UserFilled"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱地址"
            :prefix-icon="Message"
            @blur="checkEmailAvailable"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item label="部门" prop="department">
          <el-input
            v-model="registerForm.department"
            placeholder="请输入所属部门"
            :prefix-icon="OfficeBuilding"
          />
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-input
            v-model="registerForm.position"
            placeholder="请输入职位"
            :prefix-icon="Briefcase"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号码"
            :prefix-icon="Phone"
          />
        </el-form-item>

        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="registerForm.roles"
            multiple
            placeholder="请选择用户角色"
            style="width: 100%"
            :loading="roleLoading"
            :disabled="roleLoading"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
              :title="role.description"
            />
          </el-select>
          <div v-if="roleError" class="role-error">
            {{ roleError }}
            <el-button type="text" size="small" @click="loadRoles">重新加载</el-button>
          </div>
        </el-form-item>

        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意
            <el-link type="primary" @click="showAgreement">《用户协议》</el-link>
            和
            <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleRegister"
            style="width: 100%"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>

        <div class="register-footer">
          <span>已有账户？</span>
          <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </div>
      </el-form>
    </div>

    <!-- 用户协议对话框 -->
    <el-dialog
      v-model="agreementVisible"
      title="用户协议"
      width="60%"
      :before-close="handleAgreementClose"
    >
      <div class="agreement-content">
        <h3>1. 服务条款</h3>
        <p>欢迎使用项目管理系统。在使用本系统前，请仔细阅读本用户协议。</p>
        
        <h3>2. 用户责任</h3>
        <p>用户应当妥善保管账户信息，不得将账户借给他人使用。</p>
        
        <h3>3. 隐私保护</h3>
        <p>我们承诺保护用户隐私，不会泄露用户个人信息。</p>
        
        <h3>4. 服务变更</h3>
        <p>我们保留随时修改或中断服务的权利。</p>
      </div>
      <template #footer>
        <el-button @click="agreementVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 隐私政策对话框 -->
    <el-dialog
      v-model="privacyVisible"
      title="隐私政策"
      width="60%"
      :before-close="handlePrivacyClose"
    >
      <div class="privacy-content">
        <h3>1. 信息收集</h3>
        <p>我们仅收集必要的用户信息以提供服务。</p>
        
        <h3>2. 信息使用</h3>
        <p>收集的信息仅用于系统功能实现，不会用于其他目的。</p>
        
        <h3>3. 信息保护</h3>
        <p>我们采用行业标准的安全措施保护用户信息。</p>
        
        <h3>4. 信息共享</h3>
        <p>除法律要求外，我们不会与第三方共享用户信息。</p>
      </div>
      <template #footer>
        <el-button @click="privacyVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</StarfieldBackground>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  User,
  UserFilled,
  Message,
  Lock,
  OfficeBuilding,
  Briefcase,
  Phone
} from '@element-plus/icons-vue'
import { register, checkUsername } from '@/api/register'
import { getSelectableRoles, type RoleOption } from '@/api/roles'
import type { RegisterFormData, RegisterParams, UserRole } from '@/types/register'
import StarfieldBackground from '@/components/StarfieldBackground.vue'

const router = useRouter()
const registerFormRef = ref<FormInstance>()
const loading = ref(false)
const agreementVisible = ref(false)
const privacyVisible = ref(false)

// 角色相关状态
const roleOptions = ref<RoleOption[]>([])
const roleLoading = ref(false)
const roleError = ref('')

// 表单数据
const registerForm = reactive<RegisterFormData>({
  username: '',
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
  department: '',
  position: '',
  phone: '',
  roles: [],
  agreement: false
})

// 获取角色列表
const loadRoles = async () => {
  roleLoading.value = true
  roleError.value = ''
  try {
    const roles = await getSelectableRoles()
    roleOptions.value = roles
    
    // 设置默认角色为普通用户
    if (roles.length > 0) {
      const userRole = roles.find(role => role.value === 'user')
      if (userRole) {
        registerForm.roles = ['user' as UserRole]
      } else {
        // 如果没有user角色，使用第一个可用角色
        registerForm.roles = [roles[0].value as UserRole]
      }
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
    roleError.value = '加载角色列表失败，请刷新页面重试'
    ElMessage.error('加载角色列表失败')
    
    // 使用备用角色列表，默认为普通用户
    roleOptions.value = [
      { label: '普通用户', value: 'user' },
      { label: '全栈开发工程师', value: 'developer' },
      { label: '测试工程师', value: 'tester' },
      { label: '项目经理', value: 'project_manager' }
    ]
    registerForm.roles = ['user' as UserRole]
  } finally {
    roleLoading.value = false
  }
}

// 验证确认密码
const validateConfirmPassword = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 验证手机号
const validatePhone = (_rule: any, value: any, callback: any) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

// 验证用户名唯一性
const validateUsername = (_rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入用户名'))
    return
  }
  
  if (value.length < 3 || value.length > 20) {
    callback(new Error('用户名长度应在3-20个字符之间'))
    return
  }
  
  if (!/^[a-zA-Z0-9_]+$/.test(value)) {
    callback(new Error('用户名只能包含字母、数字和下划线'))
    return
  }
  
  // 异步验证用户名唯一性
  checkUsername(value).then(result => {
    if (!result.available) {
      callback(new Error('用户名已被使用'))
    } else {
      callback()
    }
  }).catch(error => {
    console.error('验证用户名失败:', error)
    callback(new Error('验证用户名失败，请稍后重试'))
  })
}

// 验证邮箱格式（简化版本，只要不为空即可）
const validateEmail = (_rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入邮箱地址'))
    return
  }
  
  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(value)) {
    callback(new Error('请输入有效的邮箱格式，例如：user@example.com'))
    return
  }
  
  // 暂时注释掉邮箱唯一性验证，只要格式正确即可
  callback()
  
  // // 异步验证邮箱唯一性
  // checkEmail(value).then(result => {
  //   if (!result.available) {
  //     callback(new Error('邮箱已被使用'))
  //   } else {
  //     callback()
  //   }
  // }).catch(error => {
  //   console.error('验证邮箱失败:', error)
  //   callback(new Error('验证邮箱失败，请稍后重试'))
  // })
}

// 表单验证规则
const registerRules: FormRules = {
  username: [
    { validator: validateUsername, trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入部门', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  agreement: [
    { 
      validator: (_rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 检查用户名可用性
const checkUsernameAvailable = async () => {
  if (!registerForm.username) return
  
  try {
    const response = await checkUsername(registerForm.username)
    if (!response.available) {
      ElMessage.warning('用户名已被使用，请选择其他用户名')
    }
  } catch (error) {
    console.error('检查用户名失败:', error)
  }
}

// 检查邮箱格式（简化版本）
const checkEmailAvailable = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请输入邮箱地址')
    return
  }
  
  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(registerForm.email)) {
    ElMessage.warning('请输入有效的邮箱格式，例如：user@example.com')
    return
  }
  
  ElMessage.success('邮箱格式正确')
  
  // 暂时注释掉邮箱唯一性检查
  // try {
  //   const response = await checkEmail(registerForm.email)
  //   if (!response.available) {
  //     ElMessage.warning('邮箱已被注册，请使用其他邮箱')
  //   } else {
  //     ElMessage.success('邮箱可以使用')
  //   }
  // } catch (error) {
  //   console.error('检查邮箱失败:', error)
  //   ElMessage.error('检查邮箱失败，请稍后重试')
  // }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    
    loading.value = true
    
    const registerParams: RegisterParams = {
      username: registerForm.username,
      name: registerForm.name,
      email: registerForm.email,
      password: registerForm.password,
      department: registerForm.department,
      position: registerForm.position,
      phone: registerForm.phone || undefined,
      roles: registerForm.roles
    }
    
    const result = await register(registerParams)
    
    if (result.success) {
      ElMessage.success('注册成功！请登录')
      router.push('/login')
    } else {
      ElMessage.error(result.message || '注册失败')
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('注册失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 显示用户协议
const showAgreement = () => {
  agreementVisible.value = true
}

// 显示隐私政策
const showPrivacy = () => {
  privacyVisible.value = true
}

// 关闭用户协议对话框
const handleAgreementClose = () => {
  agreementVisible.value = false
}

// 关闭隐私政策对话框
const handlePrivacyClose = () => {
  privacyVisible.value = false
}

// 初始化
onMounted(() => {
  loadRoles()
})

onUnmounted(() => {
  // 清理逻辑已移至StarfieldBackground组件
})
</script>

<style scoped>
.register-wrapper {
  width: 100%;
  max-width: 500px;
  position: relative;
  z-index: 1;
}

.register-card {
  width: 100%;
  max-width: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  color: #303133;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.register-header p {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.register-form {
  margin-top: 20px;
}

.register-form .el-form-item {
  margin-bottom: 20px;
}

.register-footer {
  text-align: center;
  margin-top: 20px;
  color: #909399;
  font-size: 14px;
}

.register-footer .el-link {
  margin-left: 5px;
}

.role-error {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.agreement-content,
.privacy-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.agreement-content h3,
.privacy-content h3 {
  color: #303133;
  font-size: 16px;
  margin: 20px 0 10px 0;
}

.agreement-content p,
.privacy-content p {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-container {
    padding: 10px;
  }
  
  .register-card {
    padding: 20px;
  }
  
  .register-header h2 {
    font-size: 24px;
  }
}
</style>